//
//  MainTabView.swift
//  SwiftUIProject
//
//  Created by ZhouShuai on 2024/9/11.
//

import SwiftUI

enum TabType: Int, Hashable {
    case home
    case message
    case me

    var title: String {
        switch self {
        case .home:
            return "Home"
        case .message:
            return "Message"
        case .me:
            return "Me"
        }
    }

    var image: String {
        switch self {
        case .home:
            return "house.fill"
        case .message:
            return "message.fill"
        case .me:
            return "person.fill"
        }
    }
}

struct MainTabView: View {
    @State private var selectedTab: TabType = .home

    var body: some View {
        // 创建TabView的时候，支持传入一个selection值，用来记录当前选中的tab
        // 切换tab的时候，selection读取每个子界面的tag值
        TabView(selection: $selectedTab) {
            HomeView(selectedTab: $selectedTab)
                .tabItem {
                    Text(TabType.home.title)
                    Image(systemName: TabType.home.image)
                }.tag(TabType.home)

            MessageView()
                .tabItem {
                    Text(TabType.message.title)
                    Image(systemName: TabType.message.image)
                }.tag(TabType.message)
                .badge(6)

            MeView()
                .tabItem {
                    Text(TabType.me.title)
                    Image(systemName: TabType.me.image)
                }.tag(TabType.me)
        }
        // 设置TabView的外观样式，需要使用到UIKit外观API
        .tint(Color.purple)
        .onAppear {
            UITabBar.appearance().unselectedItemTintColor = .gray
            UITabBarItem.appearance().badgeColor = .red
            UITabBar.appearance().backgroundColor = .lightGray
            UITabBarItem.appearance().titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 5)
            UITabBarItem.appearance().setBadgeTextAttributes([.foregroundColor: UIColor.white,
                                                              .font: UIFont.boldSystemFont(ofSize: 14)], for: .normal)
            UITabBarItem.appearance().setBadgeTextAttributes([.foregroundColor: UIColor.blue], for: .selected)
        }
    }
}

struct MainTabView_Previews: PreviewProvider {
    static var previews: some View {
        MainTabView()
    }
}
